package cn.syncrond.tcm.core.pool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 可暂停的线程池实现
 * @author 刘振兴
 * @date 2016-11-17
 */
public abstract class PausableThreadPoolExecutor extends ThreadPoolExecutor implements IPausable {
	
	/**
	 * 是否暂停
	 */
	protected boolean isPaused;
	
	/**
	 * 排他锁
	 */
	protected ReentrantLock lock = new ReentrantLock();
	
	/**
	 * 暂停状态
	 */
	protected Condition unpaused = lock.newCondition();
	
	public PausableThreadPoolExecutor(int nThreads){
		super(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
	}
	
	public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
	}

	public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
				threadFactory);
	}

	public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
	}

	public PausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit,
			BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
			RejectedExecutionHandler handler) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
				threadFactory, handler);
	}

	/**
	 * 暂停
	 */
	public void pause(){
		lock.lock();
		try {
			isPaused = true;
		} finally {
			lock.unlock();
		}
	}
	
	/**
	 * 恢复
	 */
	public void resume(){
		lock.lock();
		try {
			isPaused = false;
			unpaused.signalAll();
		} finally {
			lock.unlock();
		}
	}
}
